import Taro from '@tarojs/taro';
import { useState, useEffect } from 'react';
import { View, Image, Swiper, SwiperItem } from "@tarojs/components";
import { AtButton, AtToast } from 'taro-ui';
import "taro-ui/dist/style/components/article.scss";
import "taro-ui/dist/style/components/toast.scss";
import "taro-ui/dist/style/components/icon.scss";
import { praiseArticle, starArticle, cancelStarArticle } from '@/api/index';
import css from "./index.module.less";

export default function ArticleDetail(props) {
    const { id, userId, type, title, contributorName, organizationName, checkTime, content, source, reviewerName, imgAttaches, fileAttaches, browsingAmount } = props.info;

    //是否点赞
    const [isPraised, setIsPraised] = useState(0);
    //点赞样式
    const [praiseStyle, setPraiseStyle] = useState(`at-icon at-icon-heart ${css.btn}`);
    //点赞数
    const [praiseAmount, setPraiseAmount] = useState(0);
    //是否收藏
    const [isStarted, setIsStarted] = useState(0);
    //收藏样式
    const [starStyle, setStarStyle] = useState(`at-icon at-icon-star ${css.btn}`);
    //提示
    const [isOpened, setIsOpened] = useState(false);

    useEffect(() => {
        setPraiseAmount(
            props.info.isPraised === 1 ?
                props.info.praiseAmount - 1 :
                props.info.praiseAmount
        );
        setIsPraised(props.info.isPraised === 1 ? 1 : 0);
        setIsStarted(props.info.isStarted === 1 ? 1 : 0);
        if (isPraised) {
            setPraiseStyle(`at-icon at-icon-heart-2 ${css.btn} ${css.active}`);
        }
        if (isStarted) {
            setStarStyle(`at-icon at-icon-star-2 ${css.btn} ${css.active}`);
        }
    }, [props.info]);

    useEffect(() => {
        if (isPraised === 1) {
            setPraiseAmount(praiseAmount + 1);
            setPraiseStyle(`at-icon at-icon-heart-2 ${css.btn} ${css.active}`);
        }
        else {
            setPraiseAmount(praiseAmount - 1);
            setPraiseStyle(`at-icon at-icon-heart ${css.btn}`);
        }
    }, [isPraised]);

    useEffect(() => {
        if (isStarted === 1) {
            setStarStyle(`at-icon at-icon-star-2 ${css.btn} ${css.active}`);
        }
        else {
            setStarStyle(`at-icon at-icon-star ${css.btn}`);
        }
    }, [isStarted]);

    const handleDownload = (e, url) => {
        Taro.downloadFile({
            url,
            success(file) {
                Taro.openDocument({
                    filePath: file.tempFilePath,
                    success: function (res) {
                        console.log('打开文档成功', res);
                    },
                    fail: function (err) {
                        if (err.errMsg === 'openDocument:fail filetype not supported') {
                            setIsOpened(true);
                            setTimeout(() => { setIsOpened(false); }, 1000);
                        }
                    }
                });
            }
        });
    };

    const handlePraise = () => {
        const operation = isPraised === 1 ? -1 : 1;
        praiseArticle(userId, id, operation, type === 2 ? 1 : 0).then(() => { });
        setIsPraised(isPraised === 1 ? 0 : 1);
    };

    const handleStar = () => {
        if (isStarted) {
            cancelStarArticle(userId, id).then(() => { });
        }
        else {
            starArticle(userId, id).then(() => { });
        }
        setIsStarted(isStarted === 1 ? 0 : 1);
    };

    return (
        <View className={css.detail}>
            <AtToast isOpened={isOpened} text='当前文件类型无法预览' status='error' duration={0} />
            <View className={css.title}>
                {title}
            </View>
            <View className={css.info}>
                <View className={css.nameAndOrg}>
                    {contributorName}&nbsp;&nbsp;&nbsp;{organizationName}
                </View>
                <View className={css.timeAndBrowse}>
                    <View className='at-icon at-icon-clock'>
                        &nbsp;{checkTime}&nbsp;&nbsp;&nbsp;
                    </View>
                    <View className='at-icon at-icon-eye'>
                        &nbsp;{browsingAmount}
                    </View>
                </View>
            </View>
            <View className={css.image}>
                {
                    imgAttaches === undefined || imgAttaches.length === 0 ? <></> :
                        <Swiper indicatorColor='#999' indicatorActiveColor='#333' indicatorDots autoplay>
                            {
                                imgAttaches.map(item => (
                                    <SwiperItem key={item.id}>
                                        <Image src={item.path} />
                                    </SwiperItem>
                                ))
                            }
                        </Swiper>
                }
            </View>
            <View className={css.content}>
                {
                    content === undefined ? "" : content.split("\n").map((item, index) => {
                        return (<View key={index}>{item === "" ? <View></View> : item}</View>);
                    })
                }
            </View>
            <View className={css.bottomInfo}>
                来源 : {source !== undefined && source.length > 10 ? `${source.slice(0, 10)}...` : source}&nbsp;&nbsp;
                编辑 : {contributorName}&nbsp;&nbsp;
                审核 : {reviewerName}&nbsp;&nbsp;
            </View>
            <View className={css.extraFiles}>
                附件 :
                {
                    fileAttaches === undefined || fileAttaches.length === 0 ? ' 无' :
                        fileAttaches.map(item => (
                            <View key={item.id} onClick={e => handleDownload(e, item.path)}>
                                {item.name.length > 20 ? `${item.name.slice(0, 20)}...` : item.name}
                            </View>
                        ))
                }
            </View>
            <View className={css.handleBox}>
                <AtButton onClick={handlePraise} className={praiseStyle} type='secondary' circle>
                    &nbsp;{praiseAmount}
                </AtButton>
                {
                    type === '3' ? <></> :
                        <AtButton onClick={handleStar} className={starStyle} type='secondary' circle>
                            &nbsp;收藏
                        </AtButton>
                }
            </View>
        </View>

    );
}
